package com.example.threaddemo.multithread_CyclicBarrier;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

//工作线程
public class Walker implements Runnable
{
    private final CyclicBarrier mBarrier;
    private final int mThreadIndex;
    private final List<Method> mRunThreadMethodList;

    private final Object mMethodClass;

    private final List<Object[]> mParameters;

    Walker(final CyclicBarrier barrier, final int threadIndex ,final List<Method> runThreadMethods,Object methodClass,List<Object[]> parameters)
    {
        mBarrier = barrier;
        mThreadIndex = threadIndex;
        mRunThreadMethodList = runThreadMethods;
        mMethodClass = methodClass;
        mParameters = parameters;
    }

    @Override
    public void run()
    {
        // TODO Auto-generated method stub
        System.out.println("Thread " + mThreadIndex + " is running...");
        // 执行任务
        try
        {
            //线程休眠时间
            TimeUnit.MILLISECONDS.sleep(1000);
            // do task
            Method method = mRunThreadMethodList.get(mThreadIndex);
            try {
                method.invoke(mMethodClass,mParameters.get(mThreadIndex));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }

        }
        catch (InterruptedException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // 完成任务以后，等待其他线程完成任务
        try
        {
            mBarrier.await();
        }
        catch (InterruptedException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (BrokenBarrierException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 其他线程任务都完成以后，阻塞解除，可以继续接下来的任务
        System.out.println("Thread " + mThreadIndex + " do something else");
    }

}

